const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    topTips: false,
    hide: false,
    show:false,
    chain_id:0,
    payrcode:'',
    topMsg:'',
    config:{},
  },
  onLoad: function(){
    this.setData({
      config:app.globalData.appConfig
    })
    this.data.store_id = app.globalData.appConfig.store.info.id
    this.setData({
      chain_id:0,
      store_name:app.globalData.appConfig.store.info.name
    })
    this.creatCode();
  },
  //保存图片
  savephone:function(){
    var that = this;
    //判断图片权限
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.writePhotosAlbum']) {
          that.saveToPhotos();
        }else{
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success(res) {
              that.saveToPhotos();
            }
          })
        }
      },
    })
  },
  saveToPhotos:function(){
    var that = this;
    wx.downloadFile({
      url:that.data.payrcode,
      success:function(res){
        let path = res.tempFilePath
        wx.saveImageToPhotosAlbum({
          filePath: path,
          success(res) {
            that.setData({topMsg:'保存到相册成功'});
            that.topTips();
          },fail(res) {
            that.setData({topMsg:'保存到相册失败'});
            that.topTips();
          }
        })
      },fail:function(res){
        that.setData({topMsg:'保存到相册失败'});
        that.topTips();
      }
    })
  },
  //生成收款码
  creatCode:function() {
    wx.showLoading({title: '正在生成收款码',mask: true})
    app.api().Post('openapi/v1/user/MiniProgramQrCode', {
      scene: {
        store_id:this.data.store_id,
        chain_id:this.data.chain_id
      },
      page: 'pages/index/dopay',
      name: 'smartcode_'+this.data.store_id+'_'+this.data.chain_id
    },(result)=>{
      this.setData({
        payrcode: result.data,
      })
      wx.hideLoading();
    })
  },
  //切换门店二维码
  onSelect:function() {
    this.setData({
      show:!this.data.show
    })
  },
  //门店查询
  onStore(e){
    this.setData({
      store_name:e.currentTarget.dataset.name,
      chain_id:e.currentTarget.dataset.store_chain_id
    })
    this.onSelect();
    this.creatCode();
  },
  //提示显示
  topTips: function() {
    this.setData({topTips: true});
    setTimeout(() => {
      this.setData({topTips: false,hide: false,});
    },2000);
  }
})